/**   
 * Copyright © 2016 北京之洲科技有限责任公司. All rights reserved.
 * 
 * @Title: KBReflectFileOfAutoHome.java 
 * @Prject: carfactory
 * @Package: com.zizo.reflect.autohome.kb 
 * @Description: 
 * @author: Alexis  
 * @email heyan0227@outlook.com
 * @date: 2016年8月2日 下午2:23:16 
 * @version: V1.0   
 */
package com.zizo.reflect.autohome.kb;

import org.jsoup.nodes.Document;

import com.zizo.core.ReflectFile;
import com.zizo.util.DocUtil;
import com.zizo.util.Util;

/**
 * @ClassName: KBReflectFileOfAutoHome
 * @Description:
 * @author: Alexis
 * @date: 2016年8月2日 下午2:23:16
 */
public class KBReflectFileOfAutoHome extends ReflectFile {
	/**
	 * @Title:KBReflectFileOfAutoHome
	 * @Description:
	 * @param id
	 */
	public KBReflectFileOfAutoHome(String id) {
		super(id);
	}

	/**
	 * @Title: getPages
	 * @Description: 得到口碑的页数
	 * @param doc
	 * @param selectStr
	 * @return
	 * @return: int
	 * @author: Alexis
	 */
	public int getPages(Document doc, String selectStr) {
		String page = doc.select(selectStr).get(0).text();
		return Integer.parseInt(page.substring(1, page.length() - 1));
	}

	public void getItems(String url) {
		Document docPage = DocUtil.getDoc(url);
		if (docPage == null || docPage.text().length() < 200) {
			System.out.println(url);
			return;
		}
		int pages = 1;
		/* 如果口碑的帖子数大于15，则显示的页数大于1页 */
		if (docPage.select("div.page").size() > 0) {
			pages = getPages(docPage, "div.page-cont div.page span.page-item-info");
		}
		System.out.println(this.id + "开始 " + pages);
		int count = 0;
		for (int i = 1; i < pages + 1; i++) {
			String resUrl = "";
			String temp = "";
			if (url.contains("stopselling")) {
				resUrl = "http://k.autohome.com.cn/" + this.id + "/StopSelling/index_" + i + ".html";
				temp = "stopselling";
			} else {
				resUrl = "http://k.autohome.com.cn/" + this.id + "/index_" + i + ".html";
				temp = "selling";
			}
			Document doc = null;
			if (i == 1) {
				doc = docPage;
			} else {
				doc = DocUtil.getDoc(resUrl);
			}
			if (doc.text().contains("您访问的页面出错了！") || doc == null) {
				break;
			}
			Util.downloadWebsite("/var/server/autohome/kb/" + this.id + "/" + temp, i + ".html", resUrl);
			count++;
		}
		System.out.println(this.id + "结束 " + count);
	}

	/*
	 * (non Javadoc)
	 * 
	 * @Title: run
	 * 
	 * @Description:
	 * 
	 * @see com.zizo.core.ReflectFile#run()
	 */
	@Override
	public void run() {
		getItems("http://k.autohome.com.cn/" + this.id + "/");// 在售
		getItems("http://k.autohome.com.cn/" + this.id + "/stopselling/");// 停售
	}

	public static void main(String[] args) {
		KBReflectFileOfAutoHome kb = new KBReflectFileOfAutoHome("47");
		kb.getItems("http://k.autohome.com.cn/47/stopselling/");
	}

}
